//
//  SeckillResultQueryViewController.m
//  CPICApp
//
//  Created by lizhiwei on 13-3-13.
//  Copyright (c) 2013年 lizhiwei. All rights reserved.
//

#import "SeckillResultQueryViewController.h"
#import "RCAlertViewUtil.h"
#import "NSString+SBJson.h"
#import "Config.h"
#import "AppDelegate.h"
#import "UIImageView+WebCache.h"

@interface SeckillResultQueryViewController ()

@end

@implementation SeckillResultQueryViewController
@synthesize TableSeckillSuccesfullyOutline;
@synthesize GoodsName;
@synthesize GoodsSeckillTime;
@synthesize progress;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        self.title = @"秒杀结果查询";
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773@2x"]];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	
    NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
    NSString *bgimage= [accountDefaults objectForKey:@"UserDefaultBgKindKey"];
    
    if ([bgimage isEqualToString:@"蓝色主题风格"]) 
    {
        ADD_BACKGROUND_BUTTONITEM(@"icon640X88@2x.png");
        ADD_LEFT_BUTTONITEM(@"back.png");
        ADD_TITLE_NAMEITEM(@"秒杀结果查询");
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773@2x"]];
    }
    else if([bgimage isEqualToString:@"棕色主题风格"])
    {
        ADD_BACKGROUND_BUTTONITEM(@"icon640X88_01@2x.png");
        ADD_LEFT_BUTTONITEM(@"back_01.png");
        ADD_TITLE_NAMEITEM(@"秒杀结果查询");
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773_01@2x"]];
    }
    else if([bgimage isEqualToString:@"重大节日皮肤"])
    {
        NSData *dataImg_02=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_02];
        NSLog(@"-------找到%@",dataImg_02);
        NSData *dataImg_03=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_03];
        NSData *dataImg_04=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_04];
        
        NSURL *urlSkinImg_02=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_02]];
        NSURL *urlSkinImg_03=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_03]];
        NSURL *urlSkinImg_04=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_04]];
        NSLog(@"-------找到333%@",urlSkinImg_02);
        
        UIImageView * LogoImage = [[UIImageView alloc]init];
        [LogoImage setImageWithURL:urlSkinImg_03 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(LogoImage.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_03];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        LogoImage.image = [UIImage imageWithData:dataImg_03];
        LogoImage.frame = CGRectMake(0, 0, LogoImage.image.size.width/2, LogoImage.image.size.height/2);
        [self.view addSubview:LogoImage];
        
        //--------------------------
        UIButton * CallOutBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
        CallOutBtn1.frame = CGRectMake(10, 10, 109/2, 57/2);
        UIImageView * Back = [[UIImageView alloc]init];
        [Back setImageWithURL:urlSkinImg_02 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(Back.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_02];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        [Back setImage:[UIImage imageWithData:dataImg_02]];
        [CallOutBtn1 setImage:Back.image forState:UIControlStateNormal];
        [CallOutBtn1 addTarget:self action:@selector(ClickCallOutBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:CallOutBtn1];
        //--------------------------
        
        ADD_TITLE_NAMEITEM(@"秒杀结果查询");
        
        
        UIImageView *bgimage = [[UIImageView alloc]initWithFrame:CGRectMake(0,44, self.view.frame.size.width, 432)];
        [bgimage setImageWithURL:urlSkinImg_04 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(bgimage.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_04];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        [bgimage setImage:[UIImage imageWithData:dataImg_04]];
        [self.view addSubview:bgimage];
        [bgimage release];
    }
    NSLog(@"height %f",self.view.frame.size.height);
    //定义秒杀成功产品概要列表
    TableSeckillSuccesfullyOutline = [[UITableView alloc]initWithFrame:CGRectMake(0, 44, self.view.frame.size.width,self.view.frame.size.height-44)];
    TableSeckillSuccesfullyOutline.delegate = self;
	TableSeckillSuccesfullyOutline.dataSource = self;
    TableSeckillSuccesfullyOutline.backgroundView = nil;
    TableSeckillSuccesfullyOutline.autoresizingMask = UIViewContentModeTop;
    TableSeckillSuccesfullyOutline.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    TableSeckillSuccesfullyOutline.scrollEnabled = YES;
    TableSeckillSuccesfullyOutline.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:TableSeckillSuccesfullyOutline];
    
    //初始化数组
    ArrSeckillSuccesfullyOutline = [[NSMutableArray alloc]initWithObjects:
                                    @"道路救援服务",@"2013-03-12 13:40", nil];
    ArrGoodsInfo = [[NSMutableArray alloc]initWithObjects:@"产品名称:", @"价格:",@"补发短信确认码:",nil];
    
    self.GoodsName = [ArrSeckillSuccesfullyOutline objectAtIndex:0];
    self.GoodsSeckillTime = [ArrSeckillSuccesfullyOutline objectAtIndex:1];
    
    IpageNo=1;
    arrSeckillSuccessList=[[NSMutableArray alloc]init];
    
    if (_refreshHeaderView == nil)
    {
		EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.TableSeckillSuccesfullyOutline.bounds.size.height, self.view.frame.size.width, self.TableSeckillSuccesfullyOutline.bounds.size.height)];
		view.delegate = self;
		[self.TableSeckillSuccesfullyOutline addSubview:view];
		_refreshHeaderView = view;
		[view release];
    }
    //  update the last update date
	[_refreshHeaderView refreshLastUpdatedDate];
    
    [self setSeckillSuccessListRequest];
}

-(void) ClickCallOutBtn
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(tableView==TableSeckillSuccesfullyOutline)
    {
        NSLog(@"arrSeckillSuccessList count %d",[arrSeckillSuccessList count]);
        return [arrSeckillSuccessList count];
    }
    else
    {
        NSLog(@"ArrGoodsInfo count %d",[ArrGoodsInfo count]);
        return [ArrGoodsInfo count];
    }
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 45;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        static NSString *Identifier=@"Identifier";
        UITableViewCell *cell=(UITableViewCell *)[TableSeckillSuccesfullyOutline dequeueReusableCellWithIdentifier:Identifier];
    
        if (cell==nil)
        {
            UILabel *lblGoodsName=[[UILabel alloc]initWithFrame:CGRectMake(10, 9.5, 130, 21)];
            lblGoodsName.backgroundColor=[UIColor clearColor];
            lblGoodsName.font = [UIFont systemFontOfSize:11.0];
            UILabel *lblGoodsSeckillTime=[[UILabel alloc]initWithFrame:CGRectMake(135, 9.5, 80, 21)];
            lblGoodsSeckillTime.font = [UIFont systemFontOfSize:14.0];
            UILabel *lblOrderStatus=[[UILabel alloc]initWithFrame:CGRectMake(205, 9.5, 160, 21)];
            lblOrderStatus.font = [UIFont systemFontOfSize:14.0];
            
            cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifier]autorelease];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.selectionStyle=UITableViewCellSelectionStyleNone;//选中后颜色没变化
            
            lblGoodsName.tag=1;
            lblGoodsSeckillTime.tag=2;
            lblOrderStatus.tag=3;
            [cell.contentView addSubview:lblGoodsName];
            [cell.contentView addSubview:lblGoodsSeckillTime];
            [cell.contentView addSubview:lblOrderStatus];
            
            [lblGoodsName release];
            [lblGoodsSeckillTime release];
            [lblOrderStatus release];   
            /*GoodsInfobtn = [UIButton buttonWithType:UIButtonTypeCustom];
            GoodsInfobtn.frame = CGRectMake(275, 9.5, 29, 25);
            [GoodsInfobtn setImage:[UIImage imageNamed:@"login_type.png"] forState:UIControlStateNormal];
            [GoodsInfobtn addTarget:self action:@selector(GoodsInfo) forControlEvents:UIControlEventTouchUpInside];
            [cell addSubview:GoodsInfobtn];*/

        }
    NSMutableDictionary *dicSuccessList = [arrSeckillSuccessList objectAtIndex:indexPath.row];
    NSString *GoodName = [[NSString alloc] initWithFormat:@"%@",[dicSuccessList objectForKey:@"secKillCommodityName"]];
    NSString *GoodPrice = [[NSString alloc] initWithFormat:@"%@",[dicSuccessList objectForKey:@"secKillCommodityPrice"]];
    NSString *OrderStatus = [[NSString alloc] initWithFormat:@"%@",[dicSuccessList objectForKey:@"orderstatusname"]];
    UILabel *lblGoodsName111=(UILabel *)[cell viewWithTag:1];
    lblGoodsName111.text=[NSString stringWithFormat:@"%@",GoodName];
    NSLog(@"第%d行",indexPath.row);
    NSLog(@"GOOdName %@ ",GoodName);
    UILabel *lblGoodsSeckillTime111=(UILabel *)[cell viewWithTag:2];
    lblGoodsSeckillTime111.text=GoodPrice;
    UILabel *lblOrderStatus111=(UILabel *)[cell viewWithTag:3];
    lblOrderStatus111.text=OrderStatus;

    [GoodName release];
    [GoodPrice release];
    [OrderStatus release];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableDictionary *dicSuccessList = [arrSeckillSuccessList objectAtIndex:indexPath.row];
    
    NSString *secKillCommodityID = [[NSString alloc] initWithFormat:@"%@",[dicSuccessList objectForKey:@"secKillCommodityID"]];
     NSString *orderID = [[NSString alloc] initWithFormat:@"%@",[dicSuccessList objectForKey:@"orderCode"]];//订单号
    NSString *SerialNO=[[NSString alloc] initWithFormat:@"%@",[dicSuccessList objectForKey:@"orderID"]];//流水号
    SeckillResultDetailViewController *ResultDetail = [[SeckillResultDetailViewController alloc]initView:secKillCommodityID withorderID:orderID withSerialNO:SerialNO];
    [[AppDelegate app].unc pushViewController:ResultDetail animated:YES];
    ResultDetail.SeckillResultdelegate=self;
    [ResultDetail release];
}
-(void)RefreshSeckillResultQueryRequest
{
    [self viewDidLoad];
}
-(void) GoodsInfo
{
}

-(void)setSeckillSuccessListRequest//向太保移动平台发送秒杀成功信息列表请求报文
{
    NSLog(@"userinfodefault%@",[[NSUserDefaults standardUserDefaults] objectForKey:DICT_USER_INFO]);
    NSDictionary *dictUserInfo=[[NSUserDefaults standardUserDefaults] dictionaryForKey:DICT_USER_INFO];
    if (dictUserInfo!=nil) {
        if ([dictUserInfo valueForKey:@"UserAccount"]) {
            NSLog(@"%@",[dictUserInfo valueForKey:@"UserAccount"]);
        }
    }
    else
    {
//        [self justShowMessage:@"用户还没登录,请登录系统" title:@"注意"];
//        return;
    }
    
    NSString * useraccount;
    if ([dictUserInfo valueForKey:@"UserAccount"]) {
        useraccount = [dictUserInfo valueForKey:@"UserAccount"];
    }
    else
    {
        useraccount=@"cpic";
    }
//    NSString *strRequestCode=@"RequestCode=50404";
    NSString * PageNo = [[NSString alloc]initWithFormat:@"%d",IpageNo];
    NSString *strRequestData=[NSString stringWithFormat:@"{\"pageNo\":\"%@\",\"pageSize\":\"10\",\"UserAccount\":\"%@\",\"username\":\"admin11\"}",PageNo,useraccount];
//    NSString *strUrl=[NSString stringWithFormat:@"%@%@%@",Server_Url,strRequestCode,strRequestData];
//    NSLog(@"++++++++++++++%@",strUrl);
//    strUrl = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//字符串编码转换
//    
//    NSURL *myurl = [NSURL URLWithString:strUrl];//This method expects URLString to contain any necessary percent escape codes, which are ‘:’, ‘/’, ‘%’, ‘#’, ‘;’, and ‘@’. Note that ‘%’ escapes are translated via UTF-8.
//    NSLog(@"URL:%@",myurl);
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:Server_Url_Form]];
    //设置需要POST的数据，这里提交两个数据，A=a&B=b
    [request setPostValue:@"50404" forKey:@"RequestCode"];
    [request setPostValue:strRequestData forKey:@"RequestData"];
    
    [request setDelegate:self];
    [request setDidFailSelector:@selector(ResponseFail:)];
    [request setDidFinishSelector:@selector(ResonseSuccess:)];
    [request startAsynchronous];
    
    showProgress = YES;
    if (showProgress)
    {
        progress= [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:progress];
        [self.view bringSubviewToFront:progress];
        progress.labelText = @"加载中...";
        [progress show:YES];
        showProgress = NO;
    }
}

- (void)ResonseSuccess:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    
    NSString *responseString = [request responseString];
    NSLog(@"responseString %@",responseString);
    NSMutableDictionary *dictResponse=[responseString JSONValue];
    NSLog(@"dictResponse  %@",dictResponse);
    NSMutableDictionary *dictopinion=[dictResponse objectForKey:@"secKillSuccessInfoList"];

    NSMutableArray *myArrData=[dictopinion objectForKey:@"data"];
    NSLog(@"==========%@",myArrData);
    for (int i=0; i<[myArrData count]; i++) 
    {
        NSMutableDictionary *dictItem=[myArrData objectAtIndex:i];
        NSLog(@"secKillCommodityName%@",[dictItem valueForKey:@"secKillCommodityName"]);
        [arrSeckillSuccessList addObject:dictItem];
    }
    [TableSeckillSuccesfullyOutline reloadData];
    //NSLog(@"arrSeckillSuccessList %@",arrSeckillSuccessList);
    //[request release];
}

- (void)ResponseFail:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    
    NSLog(@"服务器连接失败!");
    [self justShowMessage:@"服务器连接失败！" title:@"提示"];
}

#pragma mark -
#pragma mark Data Source Loading / Reloading Methods

- (void)reloadTableViewDataSource{
	
	//  should be calling your tableviews data source model to reload
	//  put here just for demo
	_reloading = YES;
	
}

- (void)doneLoadingTableViewData{
	
	//  model should call this when its done loading
	_reloading = NO;
	[_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.TableSeckillSuccesfullyOutline];
	
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
	
	[_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	
	[_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
	
}

#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
	
	[self reloadTableViewDataSource];
	[self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:3.0];
    IpageNo=IpageNo+1;
    [self setSeckillSuccessListRequest];
	
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	
	return _reloading; // should return if data source model is reloading
	
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
	
	return [NSDate date]; // should return date data source was last changed
	
}


-(void)dealloc
{
    _refreshHeaderView = nil;
    [arrSeckillSuccessList release];
    [super dealloc];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    [TableSeckillSuccesfullyOutline release];
    [GoodsSeckillTime release];
    [GoodsName release];
    [GoodsInfobtn release];
    [progress release];
    _refreshHeaderView = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
